export const useContextMenu = (dom: Ref<HTMLDivElement | undefined>, menuDom: Ref<HTMLDivElement | undefined>) => {
    const x = ref(0)
    const y = ref(0)
    const visible = ref(false)

    const showMenu = (e:MouseEvent) => {
        e.preventDefault()
        e.stopPropagation() //阻止事件冒泡，防止子div右键菜单触发时冒泡到父div,导致父div也展示右键菜单
        x.value = e.clientX
        y.value = e.clientY
        visible.value = true
        //设置边界时不能使用transition去改变菜单高度
        nextTick(() => {
            const menuWidth = menuDom.value?.clientWidth as number
            const domWidth = dom.value?.clientWidth as number
            const menuHeight = menuDom.value?.clientHeight as number
            const domHeight = dom.value?.clientHeight as number
            if(e.offsetX + menuWidth > domWidth)
                x.value = e.clientX - menuWidth
            if(e.offsetY + menuHeight > domHeight)
                y.value = e.clientY - menuHeight
        })
    }

    const closeMenu = () => {
        visible.value = false
    }

    onMounted(() => {
        dom.value?.addEventListener('contextmenu',showMenu)
        //加上true,让监听器在捕获阶段注册
        window.addEventListener('click',closeMenu,true)
        window.addEventListener('contextmenu',closeMenu,true)
    })

    onUnmounted(() => {
        dom.value?.removeEventListener('contextmenu',showMenu)
    })

    return{
        x,
        y,
        visible
    }
}